import pandas as pd
from typing import List, Tuple, Optional


# def save_to_json(data: List[Tuple[str, str, List[str]]], filename: str) -> None:
#     """将提取的数据保存为JSON文件"""
#     json_data = [
#         {
#             "LBJTH": item[0],
#             "DN": item[1],
#             "LIST": item[2]
#         }
#         for item in data
#     ]
    
#     with open(filename, 'w', encoding=['utf-8', 'gbk', 'big5', 'iso-8859-1', 'cp936']) as f:
#         json.dump(json_data, f, ensure_ascii=False, indent=4)

def save_to_excel_simple(data: List[Tuple[str, str, Optional[str], List[str]]], filename: str):
    length = len(data[0])

    if length == 3:
        save_to_excel_three(data, filename)
    elif length == 4:
        save_to_excel_four(data, filename)
    elif length == 7:
        save_to_excel_seven(data, filename)
    else:
        print("❌ 处理失败: Invalid data length")

def save_to_excel_three(data: List[Tuple[str, str, List[str]]], filename: str) -> None:
    # 转换数据格式
    max_list_length = max(len(item[2]) for item in data)
    columns = ["LBJTH", "DN"] + [f"LIST_{i+1}" for i in range(max_list_length)]
    
    processed_data = []
    for item in data:
        lbjth, dn, lst = item
        row = {"LBJTH": lbjth, "DN": dn}
        for i in range(max_list_length):
            col_name = f"LIST_{i+1}"
            row[col_name] = lst[i] if i < len(lst) else ""
        processed_data.append(row)
    
    df = pd.DataFrame(processed_data, columns=columns)
    df.to_excel(filename, index=False, engine='openpyxl')


def save_to_excel_four(data: List[Tuple[str, str, str, List[str]]], filename: str) -> None:
    # 转换数据格式
    max_list_length = max(len(item[3]) for item in data)
    columns = ["LBJTH", "RO", "DN"] + [f"LIST_{i+1}" for i in range(max_list_length)]
    
    processed_data = []
    for item in data:
        lbjth, ro, dn, lst = item
        row = {"LBJTH": lbjth, "RO": ro, "DN": dn}
        for i in range(max_list_length):
            col_name = f"LIST_{i+1}"
            row[col_name] = lst[i] if i < len(lst) else ""
        processed_data.append(row)
    
    df = pd.DataFrame(processed_data, columns=columns)
    df.to_excel(filename, index=False, engine='openpyxl')

def save_to_excel_seven(data: List[Tuple[str, str, str, str, str, str, List[str]]], filename: str) -> None:
    # 转换数据格式
    max_list_length = max(len(item[6]) for item in data)
    columns = ["OI", "CL", "YL", "WD", "WJ", "BH"] + [f"LIST_{i+1}" for i in range(max_list_length)]
    
    processed_data = []
    for item in data:
        oi, cl, yl, wd, wj, bh, lst = item
        row = {"OI": oi, "CL": cl, "YL": yl, "WD": wd, "WJ": wj, "BH": bh}
        for i in range(max_list_length):
            col_name = f"LIST_{i+1}"
            row[col_name] = lst[i] if i < len(lst) else ""
        processed_data.append(row)
    
    df = pd.DataFrame(processed_data, columns=columns)
    df.to_excel(filename, index=False, engine='openpyxl')
